package com.hwpt.hwaccount.core.base;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import com.hwpt.hwaccount.core.data.UserTableObserver;
import com.hwpt.hwaccount.core.data.remote.RetrofitClient;
import com.hwpt.hwaccount.core.data.remote.api.ApiService;

// MyApplication.java
public class GlobalApplication extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        // 初始化 ApiService
        ApiService apiService = RetrofitClient.getApiService(this);
        
        // 设置 UserTableObserver 的 ApiService
        UserTableObserver observer = UserTableObserver.getInstance(this);
        observer.setApiService(apiService);
        
        // 注册 Activity 生命周期回调
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            private int activityCount = 0;
            
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
            
            @Override
            public void onActivityStarted(Activity activity) {
                activityCount++;
                if (activityCount == 1) {
                    // 应用从后台回到前台
                    Log.d("AppLifecycle", "应用回到前台");
                    UserTableObserver observer = UserTableObserver.getInstance(GlobalApplication.this);
                    observer.restoreObservationIfNeeded();
                }
            }
            
            @Override
            public void onActivityResumed(Activity activity) {}
            
            @Override
            public void onActivityPaused(Activity activity) {}
            
            @Override
            public void onActivityStopped(Activity activity) {
                activityCount--;
                if (activityCount == 0) {
                    // 应用进入后台
                    Log.d("AppLifecycle", "应用进入后台");
                }
            }
            
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
            
            @Override
            public void onActivityDestroyed(Activity activity) {}
        });
    }
}